#include "yt_web.h"

#include <QtCore>
#include <QtGui>
#include <QtWebKit>

#include "xmlutil.h"
#include "env.h"

#include "t_youtube_dump_lib.h"

YtWeb::YtWeb(QWebView *a_webview)
    : m_webview(a_webview)
{
    connect(m_webview->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            this, SLOT(populateJavaScriptWindowObject()));
}

void YtWeb::populateJavaScriptWindowObject()
{
    qDebug() << "YtWeb::populateJavaScriptWindowObject(ytweb)";
    m_webview->page()->mainFrame()->addToJavaScriptWindowObject("ytweb", this);
}

bool YtWeb::getFileForVideoIcon(QString a_id, QFile &a_file)
{
    QString v_deskPath =
            QDesktopServices::storageLocation(
                    QDesktopServices::DesktopLocation);
    QDir v_deskDir(v_deskPath);
    v_deskDir.mkpath("@ytcache/dl");
    QString v_cdirPath = v_deskDir.filePath("@ytcache/dl");
    QString v_iconPath = v_cdirPath + "/" + a_id + ".jpg";
    a_file.setFileName(v_iconPath);
    return a_file.exists();
}

QString YtWeb::getUrlForVideoIcon(QString a_id)
{
    QFile v_iconFile;
    getFileForVideoIcon(a_id, v_iconFile);
    if(v_iconFile.exists())
    {
        QUrl v_local_url = QUrl::fromLocalFile(v_iconFile.fileName());
        return v_local_url.toString();
    }
    QString v_remote_url = QString("http://i.ytimg.com/vi/%1/2.jpg").arg(a_id);
    return v_remote_url;
}

void YtWeb::initPage(QWebView *a_webview, QWebElement *a_webelem)
{
    QString v_html;
    v_html += "<html>\n";
    v_html += "<head>\n";
    v_html += "<link rel='stylesheet' href='qrc:/yt_list.css' type='text/css' />\n";
    v_html += "</head>\n";
    v_html += "<body>\n";
    v_html += "<div id=\"mydiv\">\n</div>\n";
    v_html += "</body>\n";
    v_html += "</html>\n";
    v_html += "<script type='text/javascript' src='qrc:/jslib/jquery.js' charset='uft-8' />\n";
    v_html += "<script type='text/javascript' src='qrc:/yt_list.js' charset='uft-8' />\n";

    //a_webview->setHtml(v_html);
    //a_webview->setUrl(QUrl("qrc:/page/page1.html"));

    QWebFrame *v_frame = a_webview->page()->mainFrame();
    (*a_webelem) = v_frame->findFirstElement("#mydiv");
    qDebug() << "[a_webelem->isNull()]" << a_webelem->isNull();
}

/*
http://code.google.com/p/get-flash-videos/source/browse/trunk/FlashVideo/Site/Youtube.pm?r=311
my @formats = (
  { id => 37, resolution => [1920, 1080] },
  { id => 22, resolution => [1280, 720] },
  { id => 35, resolution => [854, 480] },
  { id => 34, resolution => [640, 360] },
  { id => 18, resolution => [480, 270] },
  { id => 5,  resolution => [400, 224] },
  { id => 17, resolution => [176, 144] },
  { id => 13, resolution => [176, 144] },
);
*/

QUrl YtWeb::stripUrlPercentEncoding(const QUrl &a_url)
{
    QString v_removed_url = QUrl::fromPercentEncoding(a_url.toString().toLatin1());
#if 0x1
    return v_removed_url;
#else
    return a_url;
#endif
}

void YtWeb::pageVideoPlay(QWebElement *a_webelem, QString a_id, T_VideoList *a_recList)
{
    T_NetworkBatch v_nbat_1(g_Env->nam);
    v_nbat_1.get(QString("http://www.youtube.com/watch?v=%1").arg(a_id));

    QWebElement v_webelem = m_webview->page()->mainFrame()->findFirstElement("#rec_place");
    a_webelem = &v_webelem;

    QWebElement v_vlc_button_place = m_webview->page()->mainFrame()->findFirstElement("#vlc_button_place");

    v_vlc_button_place.setInnerXml("");

    QString v_inner_html = "";

    QUrl v_stream_url;
    QMap<int, QUrl> v_fmt_map;
    QStringList v_error_list;
    //QString v_token = getVideoStreamMap(a_id, v_fmt_map);
    //bool v_status = T_Youtube_Dump_Lib::getVideoStreamMap(g_Env->nam, a_id, v_fmt_map, v_error_list);
    QString v_token = T_Youtube_Dump_Lib::getVideoStreamMap(g_Env->nam, a_id, v_fmt_map, v_error_list);
    if(v_token.isEmpty())
    {
        if(v_error_list.size()>0) g_Env->showMessage(v_error_list.last());
        return;
    }
    qDebug() << "[v_token](2)" << v_token;
    int v_fmt = -1;
#if 0x0
    if(v_fmt_map.contains(34)) v_fmt = 34;
    else if(v_fmt_map.contains(5)) v_fmt = 5;
    else if(v_fmt_map.contains(35)) v_fmt = 35;
	else if(v_fmt_map.contains(18)) v_fmt = 18;
#else
    if(v_fmt_map.contains(18)) v_fmt = 18;
    else if(v_fmt_map.contains(34)) v_fmt = 34;
    else if(v_fmt_map.contains(5)) v_fmt = 5;
    else if(v_fmt_map.contains(35)) v_fmt = 35;
#endif
    if(v_fmt == -1)
    {
        return;
	}
    v_stream_url = v_fmt_map.value(v_fmt);
#if 0x0
	if(v_fmt_map.size() > 0)
	{
		QString dirPath =
				QDesktopServices::storageLocation(
						QDesktopServices::DesktopLocation);
		QDir dir(dirPath);
		QString filePath = dir.filePath("saved.m3u");
		QFile file;
		file.setFileName(filePath);
		qDebug() << file.fileName();
		file.open(QIODevice::WriteOnly | QIODevice::Truncate);
		file.write("#EXTM3U\n");
        ////file.write("#\n");
		QList<int> v_fmt_keys = v_fmt_map.keys();
		for(int i=0; i<v_fmt_keys.size(); i++)
		{
            if(i != 0) file.write("\n");
            file.write(QString("#EXTINF:0,[id=%1 fmt=%2]\n").arg(a_id).arg(v_fmt_keys.at(i)).toUtf8().constData());
            file.write(QString("%1\n").arg(v_fmt_map.value(v_fmt_keys.at(i)).toString()).toUtf8().constData());
        }
		file.close();
	}
#else
    if(v_fmt_map.size() > 0)
    {
        QString dirPath =
                QDesktopServices::storageLocation(
                        QDesktopServices::DesktopLocation);
        QDir dir(dirPath);
        QString filePath = dir.filePath("saved.asx");
        QFile file;
        file.setFileName(filePath);
        qDebug() << file.fileName();
        file.open(QIODevice::WriteOnly | QIODevice::Truncate);
        file.write("<Asx Version = \"3.0\" >\n");
        file.write("<Title>再生リスト1</Title>\n");
        file.write("<Param Name = \"AllowShuffle\" Value = \"yes\" />\n");
        ////file.write("#\n");
        QList<int> v_fmt_keys = v_fmt_map.keys();
        for(int i=0; i<v_fmt_keys.size(); i++)
        {
            int v_fmt_key = v_fmt_keys.at(i);
#if 0x0
            if(
                    (v_fmt_key != 18)
                    &&
                    (v_fmt_key != 22)
                    &&
                    (v_fmt_key != 37)
                    )
            {
                continue;
            }
#endif
            file.write("<Entry>\n");
            file.write(QString("<Title>[id=%1 fmt=%2]</Title>\n").arg(a_id).arg(v_fmt_key).toUtf8().constData());
            file.write(QString("<Ref href = \"%1\" />\n").arg(v_fmt_map.value(v_fmt_key).toString()).toLatin1().constData());
            file.write("</Entry>\n");
        }
        file.write("</Asx>\n");
        file.close();
    }
#endif

    qDebug() << "[v_fmt]" << v_fmt;

    if(v_stream_url.toString()=="")
    {
        qDebug() << "[v_fmt_map]" << v_fmt_map;
    }
    //qDebug() << "[v_stream_url]" << v_stream_url;
    qDebug() << "[v_stream_url]" << v_stream_url.toString().size();
    ////qDebug() << "[v_stream_url.toPercentEncoding()]" << QUrl::toPercentEncoding(v_stream_url.toString());

    //if(!v_stream_url.isValid()) g_Env->showMessage("HTMLからストリームURLが見つかりません");

#if 0x0
    QString v_dirPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
    QDir v_dir(v_dirPath);
    QString v_filePath = v_dir.filePath("yt_dump_03.txt");
    QFile v_file(v_filePath);
#endif

    /* VLC plugin
       http://www.videolan.org/doc/play-howto/en/ch04.html
     */
    if(v_stream_url.toString() != "")
    {
#if 0x0
        v_file.open(QFile::Append);
        v_file.write(v_inner_html.toLatin1());
#endif

        QList<int> v_fmt_keys = v_fmt_map.keys();
        foreach(int v_fmt_key, v_fmt_keys)
        {
            //qDebug() <<  "v_fmt_map.value(v_fmt_key)" << v_fmt_map.value(v_fmt_key);
            v_inner_html += QString(
                    //"<button onclick=\"fn_vlc_player('#vlc_place', '%1', 'fmt=%2')\">%1</button>"
                    "<button onclick=\"fn_vlc_player('#vlc_place', '%2', 'fmt=%1')\">%1</button>"
                    )
                    .arg(v_fmt_key)
                    .arg(v_fmt_map.value(v_fmt_key).toString())
                    //.arg(QString::fromLatin1(v_fmt_map.value(v_fmt_key).toEncoded()))
                    //.arg(v_fmt_map.value(v_fmt_key).toString().toLatin1())
                    //.arg(QUrl::toPercentEncoding(v_fmt_map.value(v_fmt_key).toString()))
                    //.arg(QString::fromLatin1(v_fmt_map.value(v_fmt_key).toEncoded()))
                    //.arg(QString::fromLatin1(v_fmt_map.value(v_fmt_key).toString().toLatin1().toPercentEncoding()))
                    ;
#if 0x0
            v_file.write("[1]");
            v_file.write(v_fmt_map.value(v_fmt_key).toString().toLatin1());
            v_file.write("\n");
#endif
        }
        //"<button onclick=\"fn_vlc_player('#vlc_place', '%1')\">zzz</button>"

#if 0x0
        v_file.write("[2]");
        v_file.write(v_inner_html.toLatin1());
        v_file.write("\n");
        v_file.close();
#endif

        //qDebug() << v_inner_html;
        v_vlc_button_place.appendInside(v_inner_html);
		emit answer_vlc_player(v_stream_url.toString(), QString("fmt=%1").arg(v_fmt));
		//emit answer_yt_player(a_id, a_id);
	}

    if(!a_recList) return;
    v_inner_html = "";
    for (int i=0; i<a_recList->size(); i++)
    {
		QString v_id = a_recList->value(i)->id;
		QString v_title = a_recList->value(i)->title;
        v_title = Qt::escape(v_title);
		qint64 v_view_count = a_recList->value(i)->view_count;
        QString v_append =
                QString(
                        "<div id='outer_%1'>"
                        "<table border=0><tr>"
                        "  <td>"
                        //"<image  width=120 height=90 "
                        "<image src='%4' width=120 height=90 "
						"onclick='web1.submitIdToPlay(\"%1\");' "
                        "/>"
                        "  </td>"
                        "  <td>"
                        "    %2<br />"
						"    <button onclick='web1.submitIdToPlay(\"%1\");'>再生</button>"
						"    <a href='http://www.youtube.com/watch?v=%1'>再生2</a>"
                        "    <button onclick='fn_del_image(\"%1\");'>隠す</button>"
                        "    [%L3 回]"
                        "  </td>"
                        "</table>"
                        "</div>"
                        )
                .arg(v_id)
                .arg(v_title)
                .arg(v_view_count)
                .arg(YtWeb::getUrlForVideoIcon(v_id))
                ;
        //qDebug() << v_append;

        v_inner_html += v_append;
    }
    a_webelem->setInnerXml("");
    a_webelem->appendInside(v_inner_html);

}

